package com.tqjc.utils;

import com.alibaba.fastjson.JSONObject;
import com.tqjc.entity.Connect;
import com.tqjc.entity.PlcPointEntity;
import com.tqjc.entity.Point;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.web.client.RestTemplate;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

@Slf4j
public class HttpUtils {



    public static void main(String[] args) {

    }

    public static Map<String, Integer> dataTypeList = new HashMap();

    static {
        dataTypeList.put("bool", 0);
        dataTypeList.put("byte", 1);
        dataTypeList.put("int16", 2);
        dataTypeList.put("uint16", 3);
        dataTypeList.put("int32", 4);
        dataTypeList.put("uint32", 5);
        dataTypeList.put("float", 6);
        dataTypeList.put("int64", 7);
        dataTypeList.put("uint64", 8);
        dataTypeList.put("double", 9);
        dataTypeList.put("string", 10);
    }


    public static void plcWritebc(RestTemplate restTemplate, String host, String mac_sn, String address, int dataType, String value) {
        HttpHeaders headers = new HttpHeaders();
        String url = host + "/api/Data/writebc";
        Map<String, Object> body = new HashMap<>();
        body.put("mac_sn", mac_sn);
        body.put("address", address);
        body.put("dataType", dataType);
        body.put("values", value);
        headers.setContentType(MediaType.APPLICATION_JSON);
        headers.set("Accept", "application/json");
        HttpEntity httpEntity = new HttpEntity<>(body, headers);
        String resultPost = restTemplate.postForObject(url, httpEntity, String.class);
        JSONObject jsonObject = JSONObject.parseObject(resultPost, JSONObject.class);
        if (null != jsonObject) {
            if ((Boolean) jsonObject.get("result")) {
//                log.info("本次写入plc成功，写入值==>" + value);
            } else {
                log.error("本次写入plc失败成功，准备写入的点位是{},准备写入的值是{}", address, value);
            }
        }
    }

    public static String plcSn226 = "BakS_1a5f5e2fea04423ea011f312c78789d0";
    public static String plcSn227 = "BakS_a8d5af79d46d4f12afee74cee7e8c05a";

    public static void plcWritebcPlus(RestTemplate restTemplate, String host, String mac_sn, String address, int dataType, String value,String readSn,String label){
        long start = System.currentTimeMillis();
        if(!"true".equalsIgnoreCase(plcReadbc(restTemplate,host,readSn,readSn.equals(plcSn227)?"A主启动":"B主启动"))){
            log.error(readSn.equals(plcSn227)?"1号":"2号"+"车的主启动不是true，请确保该车的plc处于正常通讯状态在进行写点操作！！预备写入的点位名称是："+label);
            return;
        }

        while (true){
            plcWritebc(restTemplate,host,mac_sn,address,dataType,value);
            String wantValue = plcReadbc(restTemplate,host,readSn,label);
            if(wantValue.equalsIgnoreCase(value)){
                break;
            }
            if(System.currentTimeMillis() - start > 10*1000){
                log.error("往macSn={},写入点位{}={}超时。",mac_sn,address,value);
                break;
            }
            try {
                Thread.sleep(1);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }


    public static String plcReadbc(RestTemplate restTemplate, String host, String sn, String label) {
        HttpHeaders headers = new HttpHeaders();
        String url = host + "/api/Data/Readbc";
        Map<String, Object> body = new HashMap<>();
        body.put("sn", sn);
        body.put("label", label);
        headers.setContentType(MediaType.APPLICATION_JSON);
        headers.set("Accept", "application/json");
        HttpEntity httpEntity = new HttpEntity<>(body, headers);
        String resultPost = restTemplate.postForObject(url, httpEntity, String.class);
        JSONObject jsonObject = JSONObject.parseObject(resultPost, JSONObject.class);
        if (null != jsonObject) {
            if ((Boolean) jsonObject.get("result")) {
                JSONObject content = jsonObject.getJSONObject("content");
                String currentVal = content.getString("currentVal");
//                log.info("currentVal==" + currentVal);
                return currentVal;
            } else {
                log.error("本次读plc失败，准备读的点位是{}", label);
            }
        }
        return "";
    }


    public static String plcRead(RestTemplate restTemplate, String host, Connect connect, Point point) {
        HttpHeaders headers = new HttpHeaders();
        Map<String, Object> body = new HashMap<>();
        body.put("connect", connect);
        body.put("point", point);
        String url = host + "/api/Data/Read";
        headers.setContentType(MediaType.APPLICATION_JSON);
        headers.set("Accept", "application/json");
        HttpEntity httpEntity = new HttpEntity<>(body, headers);
        String resultPost = restTemplate.postForObject(url, httpEntity, String.class);
//        String resultPost = sendPost(url, JSONObject.toJSONString(body));
        // 返回结果
        JSONObject jsonObject = JSONObject.parseObject(resultPost, JSONObject.class);
        if (null != jsonObject) {
            if ((Boolean) jsonObject.get("result")) {
                JSONObject content = jsonObject.getJSONObject("content");
                String currentVal = content.getString("currentVal");
//                log.info("currentVal=="+currentVal);
                return currentVal;
            }
        }
        return "";
    }


    public static Map<String,String> writeValueToPlc(ArrayList<PlcPointEntity> list, RestTemplate restTemplate, String host) {
        Map<String,String> result = new HashMap<String,String>();
        list.stream().forEach(e -> {
            long begin = System.currentTimeMillis();
            while(!HttpUtils.plcReadbc(restTemplate, host,e.getReadPlcSn(),e.getLabel()).equalsIgnoreCase(e.getExpectValue())){
                if(System.currentTimeMillis() - begin>2000){
                    result.put(e.getLabel(),"写入点位"+e.getLabel()+"超时");
                    break;
                }
                HttpUtils.plcWritebc(restTemplate, host, e.getWriteMacSn(), e.getAddress(), e.getPointType(), e.getExpectValue());
            }
        });
        return result;

//        String macSn = car == 1 ? "4#GL227" : "4#GL226";
//        String plcReadSn = car == 1 ? plcSn227 : plcSn226;
//        ArrayList list = new ArrayList();
//        PlcPointEntity point = new PlcPointEntity();
//        point.setAddress("DB1.0.0");
//        point.setPointType(HttpUtils.dataTypeList.get("bool"));
//        point.setLabel(car == 1 ? "A主接触器上电" : "B主接触器上电");
//        point.setExpectValue("TRUE");
//        point.setWriteMacSn(macSn);
//        point.setReadPlcSn(plcReadSn);
//        list.add(point);
//        Map result = HttpUtils.writeValueToPlc(list, restTemplate, host);
//        if(result.size()!=0){
//            return "fail";
//        }
//        return "ok";

    }

    /**
     * 向指定 URL 发送POST方法的请求
     *
     * @param url   发送请求的 URL
     * @param param 请求参数，请求参数应该是 JSONObject.toJSONString(param) 的形式。
     * @return 所代表远程资源的响应结果
     */
//    public static String sendPost(String url, String param) {
//        PrintWriter out = null;
//        BufferedReader in = null;
//        String result = "";
//        try {
//            URL realUrl = new URL(url);
//            // 打开和URL之间的连接
//            URLConnection conn = realUrl.openConnection();
//            // 设置通用的请求属性
//            conn.setRequestProperty("accept", "*/*");
//            conn.setRequestProperty("connection", "Keep-Alive");
//            conn.setRequestProperty("user-agent",
//                    "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
//            conn.setRequestProperty("Content-Type", "application/json;charset=UTF-8");
//            // 发送POST请求必须设置如下两行
//            conn.setDoOutput(true);
//            conn.setDoInput(true);
//            // 获取URLConnection对象对应的输出流
//            out = new PrintWriter(conn.getOutputStream());
//            // 发送请求参数
//            out.print(param);
//            // flush输出流的缓冲
//            out.flush();
//            // 定义BufferedReader输入流来读取URL的响应
//            in = new BufferedReader(
//                    new InputStreamReader(conn.getInputStream()));
//            String line;
//            while ((line = in.readLine()) != null) {
//                result += line;
//            }
//        } catch (Exception e) {
//            System.out.println("发送 POST 请求出现异常！" + e.getMessage());
//            e.printStackTrace();
//        }
//        //使用finally块来关闭输出流、输入流
//        finally {
//            try {
//                if (out != null) {
//                    out.close();
//                }
//                if (in != null) {
//                    in.close();
//                }
//            } catch (IOException ex) {
//                ex.printStackTrace();
//            }
//        }
//        return result;
//    }
}

